2. Deep Learning: A Simple Example¶
Let’s get back to the Name Gender Classifier.

2.1. Prepare Data¶
## Packages Dependencies
import os
import shutil
import numpy as np
import nltk
from nltk.corpus import names
import random
from sklearn.model_selection import train_test_split
from sklearn.manifold import TSNE
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['figure.dpi'] = 150
from lime.lime_text import LimeTextExplainer
import tensorflow as tf
import tensorflow.keras as keras
from keras.preprocessing.text import Tokenizer
from keras.preprocessing import sequence
from keras.utils import to_categorical, plot_model
from keras.models import Sequential
from keras import layers
# from keras.layers import Dense
# from keras.layers import LSTM, RNN, GRU
# from keras.layers import Embedding
# from keras.layers import SpatialDropout1D
import kerastuner
labeled_names = ([(name, 1) for name in names.words('male.txt')] +
[(name, 0) for name in names.words('female.txt')])
random.shuffle(labeled_names)
2.2. Train-Test Split¶
train_set, test_set = train_test_split(labeled_names,
test_size=0.2,
random_state=42)
print(len(train_set), len(test_set))
6355 1589
names = [n for (n, l) in train_set] ## X
labels = [l for (n, l) in train_set] ## y
len(names)
6355
2.3. Tokenizer¶
keras.preprocessing.text.Tokenizeris a very useful tokenizer for text processing in deep learning.Tokenizerassumes that the word tokens of the input texts have been delimited by whitespaces.Tokenizerprovides the following functions:It will first create a dictionary for the entire corpus (a mapping of each word token and its unique integer index index) (
Tokenizer.fit_on_text())It can then use the corpus dictionary to convert words in each corpus text into integer sequences (
Tokenizer.texts_to_sequences())The dictionary is in
Tokenizer.word_index
Notes on
Tokenizer:By default, the token index 0 is reserved for padding token.
If
oov_tokenis specified, it is default to index 1. (Default:oov_token=False)Specify
num_words=NforTokenizerto include only top N words in converting texts to sequences.Tokenizerwill automatically remove punctuations.Tokenizeruse the whitespace as word-token delimiter.If every character is treated as a token, specify
char_level=True.Please read
Tokenizerdocumentation very carefully. Very important!!
tokenizer = Tokenizer(char_level=True)
tokenizer.fit_on_texts(names) ## similar to CountVectorizer.fit_transform()
Vocabulary¶
After we Tokenizer.fit_on_texts(), we can take a look at the corpus dictionary, i.e., the mapping of words and their unique integer indices.
# determine the vocabulary size
vocab_size = len(tokenizer.word_index) + 1
print('Vocabulary Size: %d' % vocab_size)
Vocabulary Size: 29
tokenizer.word_index
{'a': 1,
'e': 2,
'i': 3,
'n': 4,
'r': 5,
'l': 6,
'o': 7,
't': 8,
's': 9,
'd': 10,
'y': 11,
'm': 12,
'h': 13,
'c': 14,
'b': 15,
'u': 16,
'g': 17,
'k': 18,
'j': 19,
'v': 20,
'f': 21,
'p': 22,
'w': 23,
'z': 24,
'x': 25,
'q': 26,
'-': 27,
' ': 28}
2.4. Prepare Input and Output Tensors¶
Like in feature-based machine learning, a computational model only accepts numeric values. It is necessary to convert raw texts to numeric tensors for neural network.
After we create the
Tokenizer, we use theTokenizerto perform text vectorization, i.e., converting texts into tensors.In deep learning, words or characters are automatically converted into numeric representations. In other words, the feature engineering step is fully automatic.
Two Ways of Text Vectorization¶
Texts to Sequences:
For each text, we convert all word tokens into integer sequences.
These integer sequences will then be transformed into embeddings in the deep learning network.
These embeddings are usually the basis for deep learning sequence models (i.e., RNN).
Texts to Matrix:
For each text, we vectorize the entire text into a vector of bag-of-words representation.
A One-hot encoding of the entire text would have all values of the text vector to be either 0 or 1, indicating the occurrence of all the words in the dictionary.
We can of course use the frequency-based bag-of-words representation (similar to
CountVectorizer()).
2.5. Method 1: Text to Sequences¶
From Texts and Sequences¶
We can convert our corpus texts into integer sequences using
Tokenizer.texts_to_sequences().Because texts vary in lengths, we use
keras.preprocessing.sequence.pad_sequence()to pad all texts into a uniform length.This step is important. This ensures that every text, when pushed into the network, has exactly the same tensor shape.
names_ints = tokenizer.texts_to_sequences(names)
print(names[:5])
print(names_ints[:5])
print(labels[:5])
['Troy', 'Karrah', 'Antoni', 'Sabra', 'Smitty']
[[8, 5, 7, 11], [18, 1, 5, 5, 1, 13], [1, 4, 8, 7, 4, 3], [9, 1, 15, 5, 1], [9, 12, 3, 8, 8, 11]]
[1, 0, 1, 0, 1]
Padding¶
When padding the all texts into uniform lengths, consider whether to pad or remove values from the beginning of the sequence (i.e.,
pre) or the other way (post).Check
paddingandtruncatingparameters inpad_sequencesIn this tutorial, we first identify the longest name, and use its length as the
max_lenand pad all names into themax_len.
## We can check the length distribution of texts in corpus
names_lens = [len(n) for n in names_ints]
names_lens
sns.displot(names_lens)
print(names[np.argmax(names_lens)]) # longest name
Jean-Christophe
max_len = names_lens[np.argmax(names_lens)]
max_len
15
names_ints_pad = sequence.pad_sequences(names_ints, maxlen=max_len)
names_ints_pad[:10]
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 5, 7, 11],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 1, 5, 5, 1, 13],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 8, 7, 4, 3],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 1, 15, 5, 1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 12, 3, 8, 8, 11],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 16, 3, 4, 8],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 1, 6, 6, 1, 12],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 3, 4, 7, 10],
[ 0, 0, 0, 0, 0, 0, 0, 19, 7, 9, 9, 2, 6, 11, 4],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 16, 5, 18, 2]],
dtype=int32)
Define X and y¶
So for names, we convert names into integer sequences, and pad them into the uniform length.
We perform exactly the same processing to the names in testing data.
We convert both the names (X) and labels (y) into
numpy.array.
## training data
X_train = np.array(names_ints_pad).astype('int32')
y_train = np.array(labels)
## testing data
X_test_texts = [n for (n, l) in test_set]
X_test = np.array(
sequence.pad_sequences(tokenizer.texts_to_sequences(X_test_texts),
maxlen=max_len)).astype('int32')
y_test = np.array([l for (n, l) in test_set])
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
(6355, 15)
(6355,)
(1589, 15)
(1589,)
2.6. Method 2: Text to Matrix¶
One-Hot Encoding (Bag-of-Words)¶
We can convert each text to a bag-of-words vector using
Tokenzier.texts_to_matrix().In particular, we can specify the parameter
mode:binary,count, ortfidf.When the
mode="binary", the text vector is a one-hot encoding vector, indicating whether a character occurs in the text or not.
names_matrix = tokenizer.texts_to_matrix(names, mode="binary")
print(names_matrix.shape)
(6355, 29)
print(names[2])
print(names_matrix[2,:])
Antoni
[0. 1. 0. 1. 1. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0.]
tokenizer.word_index
{'a': 1,
'e': 2,
'i': 3,
'n': 4,
'r': 5,
'l': 6,
'o': 7,
't': 8,
's': 9,
'd': 10,
'y': 11,
'm': 12,
'h': 13,
'c': 14,
'b': 15,
'u': 16,
'g': 17,
'k': 18,
'j': 19,
'v': 20,
'f': 21,
'p': 22,
'w': 23,
'z': 24,
'x': 25,
'q': 26,
'-': 27,
' ': 28}
Define X and Y¶
X_train2 = np.array(names_matrix).astype('int32')
y_train2 = np.array(labels)
X_test2 = tokenizer.texts_to_matrix(X_test_texts,
mode="binary").astype('int32')
y_test2 = np.array([l for (n, l) in test_set])
print(X_train2.shape)
print(y_train2.shape)
print(X_test2.shape)
print(y_test2.shape)
(6355, 29)
(6355,)
(1589, 29)
(1589,)
2.7. Model Definition¶
Three important steps for building a deep neural network:
Define the model structure
Compile the model
Fit the model
After we have defined our input and output tensors (X and y), we can define the architecture of our neural network model.
For the two ways of name vectorized representations, we try two different types of networks.
Text to Matrix: Fully connected Dense Layers
Text to Sequences: Embedding + RNN
# Two Versions of Plotting Functions for `history` from `model.fit()`
def plot1(history):
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
## Accuracy plot
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
## Loss plot
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
def plot2(history):
pd.DataFrame(history.history).plot(figsize=(8, 5))
plt.grid(True)
#plt.gca().set_ylim(0,1)
plt.show()
Model 1: Fully Connected Dense Layers¶
Let’s try a simple neural network with two fully-connected dense layers with the Text-to-Matrix inputs.
That is, the input of this model is the bag-of-words representation of the entire name.

Dense Layer Operation¶
The transformation of each Dense layer will transform the input tensor into a tensor whose dimension size is the same as the node number of the Dense layer.

## Define Model
model1 = keras.Sequential()
model1.add(keras.Input(shape=(vocab_size, ), name="one_hot_input"))
model1.add(layers.Dense(16, activation="relu", name="dense_layer_1"))
model1.add(layers.Dense(16, activation="relu", name="dense_layer_2"))
model1.add(layers.Dense(1, activation="sigmoid", name="output"))
## Compile Model
model1.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=["accuracy"])
plot_model(model1, show_shapes=True)
A few hyperparameters for network training¶
Batch Size: The number of inputs needed per update of the model parameter (gradient descent)
Epoch: How many iterations needed for training
Validation Split Ratio: Proportion of validation and training data split
## Hyperparameters
BATCH_SIZE = 128
EPOCHS = 20
VALIDATION_SPLIT = 0.2
## Fit the model
history1 = model1.fit(X_train2,
y_train2,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
verbose=2,
validation_split=VALIDATION_SPLIT)
Epoch 1/20
40/40 - 1s - loss: 0.6889 - accuracy: 0.5413 - val_loss: 0.6530 - val_accuracy: 0.6294
Epoch 2/20
40/40 - 0s - loss: 0.6516 - accuracy: 0.6247 - val_loss: 0.6373 - val_accuracy: 0.6357
Epoch 3/20
40/40 - 0s - loss: 0.6375 - accuracy: 0.6343 - val_loss: 0.6259 - val_accuracy: 0.6467
Epoch 4/20
40/40 - 0s - loss: 0.6230 - accuracy: 0.6446 - val_loss: 0.6154 - val_accuracy: 0.6617
Epoch 5/20
40/40 - 0s - loss: 0.6090 - accuracy: 0.6662 - val_loss: 0.6063 - val_accuracy: 0.6758
Epoch 6/20
40/40 - 0s - loss: 0.5974 - accuracy: 0.6758 - val_loss: 0.5988 - val_accuracy: 0.6837
Epoch 7/20
40/40 - 0s - loss: 0.5883 - accuracy: 0.6863 - val_loss: 0.5927 - val_accuracy: 0.6908
Epoch 8/20
40/40 - 0s - loss: 0.5814 - accuracy: 0.6916 - val_loss: 0.5894 - val_accuracy: 0.7018
Epoch 9/20
40/40 - 0s - loss: 0.5776 - accuracy: 0.6981 - val_loss: 0.5838 - val_accuracy: 0.7042
Epoch 10/20
40/40 - 0s - loss: 0.5721 - accuracy: 0.7020 - val_loss: 0.5795 - val_accuracy: 0.7136
Epoch 11/20
40/40 - 0s - loss: 0.5688 - accuracy: 0.7079 - val_loss: 0.5760 - val_accuracy: 0.7026
Epoch 12/20
40/40 - 0s - loss: 0.5659 - accuracy: 0.7077 - val_loss: 0.5751 - val_accuracy: 0.7010
Epoch 13/20
40/40 - 0s - loss: 0.5635 - accuracy: 0.7099 - val_loss: 0.5760 - val_accuracy: 0.7018
Epoch 14/20
40/40 - 0s - loss: 0.5609 - accuracy: 0.7118 - val_loss: 0.5699 - val_accuracy: 0.7097
Epoch 15/20
40/40 - 0s - loss: 0.5588 - accuracy: 0.7156 - val_loss: 0.5707 - val_accuracy: 0.7010
Epoch 16/20
40/40 - 0s - loss: 0.5572 - accuracy: 0.7150 - val_loss: 0.5668 - val_accuracy: 0.7034
Epoch 17/20
40/40 - 0s - loss: 0.5544 - accuracy: 0.7172 - val_loss: 0.5657 - val_accuracy: 0.7089
Epoch 18/20
40/40 - 0s - loss: 0.5532 - accuracy: 0.7146 - val_loss: 0.5649 - val_accuracy: 0.7113
Epoch 19/20
40/40 - 0s - loss: 0.5513 - accuracy: 0.7175 - val_loss: 0.5653 - val_accuracy: 0.7018
Epoch 20/20
40/40 - 0s - loss: 0.5492 - accuracy: 0.7205 - val_loss: 0.5622 - val_accuracy: 0.7144
plot1(history1)
model1.evaluate(X_test2, y_test2, batch_size=BATCH_SIZE, verbose=2)
13/13 - 0s - loss: 0.5707 - accuracy: 0.7067
[0.5706567168235779, 0.7067338228225708]
Model 2: Embedding + RNN¶
Another possibility is to introduce an embedding layer in the network, which transforms each character of the name into a tensor (i.e., embeddings), and then we add a Recurrent Neural Network (RNN) layer to process each character sequentially.
The strength of the RNN is that it iterates over the timesteps of a sequence, while maintaining an internal state that encodes information about the timesteps it has seen so far.
It is posited that after the RNN iterates through the entire sequence, it keeps important information of all previously iterated tokens for further operation.
The input of this network is a padded sequence of the original text (name).

## Define the embedding dimension
EMBEDDING_DIM = 128
## Define model
model2 = Sequential()
model2.add(
layers.Embedding(input_dim=vocab_size,
output_dim=EMBEDDING_DIM,
input_length=max_len,
mask_zero=True))
model2.add(layers.SimpleRNN(16, activation="relu", name="RNN_layer"))
model2.add(layers.Dense(16, activation="relu", name="dense_layer"))
model2.add(layers.Dense(1, activation="sigmoid", name="output"))
model2.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=["accuracy"])
Embedding Layer Operation¶

RNN Layer Operation¶

RNN Layer Operation¶

Unrolled Version of RNN Operation¶

Unrolled Version of RNN Operation¶

plot_model(model2, show_shapes=True)
history2 = model2.fit(X_train,
y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
verbose=2,
validation_split=VALIDATION_SPLIT)
Epoch 1/20
40/40 - 1s - loss: 0.6264 - accuracy: 0.7276 - val_loss: 0.5326 - val_accuracy: 0.7679
Epoch 2/20
40/40 - 0s - loss: 0.4706 - accuracy: 0.7856 - val_loss: 0.4479 - val_accuracy: 0.7718
Epoch 3/20
40/40 - 0s - loss: 0.4269 - accuracy: 0.7960 - val_loss: 0.4397 - val_accuracy: 0.7860
Epoch 4/20
40/40 - 0s - loss: 0.4127 - accuracy: 0.8037 - val_loss: 0.4365 - val_accuracy: 0.7773
Epoch 5/20
40/40 - 0s - loss: 0.4061 - accuracy: 0.8066 - val_loss: 0.4357 - val_accuracy: 0.7821
Epoch 6/20
40/40 - 0s - loss: 0.4015 - accuracy: 0.8102 - val_loss: 0.4311 - val_accuracy: 0.7860
Epoch 7/20
40/40 - 0s - loss: 0.3951 - accuracy: 0.8116 - val_loss: 0.4294 - val_accuracy: 0.7923
Epoch 8/20
40/40 - 0s - loss: 0.3892 - accuracy: 0.8147 - val_loss: 0.4308 - val_accuracy: 0.7915
Epoch 9/20
40/40 - 0s - loss: 0.3850 - accuracy: 0.8125 - val_loss: 0.4348 - val_accuracy: 0.7891
Epoch 10/20
40/40 - 0s - loss: 0.3807 - accuracy: 0.8208 - val_loss: 0.4389 - val_accuracy: 0.7828
Epoch 11/20
40/40 - 0s - loss: 0.3811 - accuracy: 0.8194 - val_loss: 0.4312 - val_accuracy: 0.7939
Epoch 12/20
40/40 - 0s - loss: 0.3733 - accuracy: 0.8210 - val_loss: 0.4332 - val_accuracy: 0.8002
Epoch 13/20
40/40 - 0s - loss: 0.3713 - accuracy: 0.8240 - val_loss: 0.4342 - val_accuracy: 0.7931
Epoch 14/20
40/40 - 0s - loss: 0.3673 - accuracy: 0.8269 - val_loss: 0.4303 - val_accuracy: 0.7962
Epoch 15/20
40/40 - 0s - loss: 0.3672 - accuracy: 0.8263 - val_loss: 0.4274 - val_accuracy: 0.7954
Epoch 16/20
40/40 - 0s - loss: 0.3608 - accuracy: 0.8304 - val_loss: 0.4270 - val_accuracy: 0.7994
Epoch 17/20
40/40 - 0s - loss: 0.3576 - accuracy: 0.8326 - val_loss: 0.4285 - val_accuracy: 0.8002
Epoch 18/20
40/40 - 0s - loss: 0.3575 - accuracy: 0.8324 - val_loss: 0.4246 - val_accuracy: 0.8002
Epoch 19/20
40/40 - 0s - loss: 0.3546 - accuracy: 0.8332 - val_loss: 0.4242 - val_accuracy: 0.8072
Epoch 20/20
40/40 - 0s - loss: 0.3571 - accuracy: 0.8340 - val_loss: 0.4318 - val_accuracy: 0.7970
plot1(history2)
model2.evaluate(X_test, y_test, batch_size=BATCH_SIZE, verbose=2)
13/13 - 0s - loss: 0.4494 - accuracy: 0.7936
[0.4493768513202667, 0.7935808897018433]
Model 3: Regularization and Dropout¶
Based on the validation results of the previous two models (esp. the RNN-based model), we can see that they are probably a bit overfit because the model performance on the validation set starts to stall after the first few epochs.
We can add regularization and dropouts in our network definition to avoid overfitting.
## Define embedding dimension
EMBEDDING_DIM = 128
## Define model
model3 = Sequential()
model3.add(
layers.Embedding(input_dim=vocab_size,
output_dim=EMBEDDING_DIM,
input_length=max_len,
mask_zero=True))
model3.add(
layers.SimpleRNN(16,
activation="relu",
name="RNN_layer",
dropout=0.2, ## dropout for input character
recurrent_dropout=0.2)) ## dropout for previous state
model3.add(layers.Dense(16, activation="relu", name="dense_layer"))
model3.add(layers.Dense(1, activation="sigmoid", name="output"))
model3.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=["accuracy"])
plot_model(model3, show_shapes=True)
history3 = model3.fit(X_train,
y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
verbose=2,
validation_split=VALIDATION_SPLIT)
Epoch 1/20
40/40 - 2s - loss: 0.6175 - accuracy: 0.6292 - val_loss: 0.5392 - val_accuracy: 0.6609
Epoch 2/20
40/40 - 0s - loss: 0.5147 - accuracy: 0.7105 - val_loss: 0.4926 - val_accuracy: 0.7569
Epoch 3/20
40/40 - 0s - loss: 0.4844 - accuracy: 0.7695 - val_loss: 0.4745 - val_accuracy: 0.7695
Epoch 4/20
40/40 - 0s - loss: 0.4639 - accuracy: 0.7823 - val_loss: 0.4563 - val_accuracy: 0.7742
Epoch 5/20
40/40 - 0s - loss: 0.4493 - accuracy: 0.7864 - val_loss: 0.4449 - val_accuracy: 0.7821
Epoch 6/20
40/40 - 0s - loss: 0.4415 - accuracy: 0.7825 - val_loss: 0.4381 - val_accuracy: 0.7899
Epoch 7/20
40/40 - 0s - loss: 0.4365 - accuracy: 0.7886 - val_loss: 0.4353 - val_accuracy: 0.7852
Epoch 8/20
40/40 - 0s - loss: 0.4313 - accuracy: 0.7895 - val_loss: 0.4322 - val_accuracy: 0.7915
Epoch 9/20
40/40 - 0s - loss: 0.4285 - accuracy: 0.7945 - val_loss: 0.4303 - val_accuracy: 0.7860
Epoch 10/20
40/40 - 0s - loss: 0.4245 - accuracy: 0.7917 - val_loss: 0.4277 - val_accuracy: 0.7978
Epoch 11/20
40/40 - 0s - loss: 0.4237 - accuracy: 0.7915 - val_loss: 0.4250 - val_accuracy: 0.7931
Epoch 12/20
40/40 - 0s - loss: 0.4216 - accuracy: 0.7990 - val_loss: 0.4245 - val_accuracy: 0.7915
Epoch 13/20
40/40 - 0s - loss: 0.4198 - accuracy: 0.7909 - val_loss: 0.4225 - val_accuracy: 0.7954
Epoch 14/20
40/40 - 0s - loss: 0.4224 - accuracy: 0.7948 - val_loss: 0.4221 - val_accuracy: 0.7939
Epoch 15/20
40/40 - 0s - loss: 0.4135 - accuracy: 0.7931 - val_loss: 0.4181 - val_accuracy: 0.8033
Epoch 16/20
40/40 - 0s - loss: 0.4169 - accuracy: 0.7960 - val_loss: 0.4212 - val_accuracy: 0.8009
Epoch 17/20
40/40 - 0s - loss: 0.4127 - accuracy: 0.7992 - val_loss: 0.4183 - val_accuracy: 0.7931
Epoch 18/20
40/40 - 0s - loss: 0.4144 - accuracy: 0.7990 - val_loss: 0.4184 - val_accuracy: 0.8025
Epoch 19/20
40/40 - 0s - loss: 0.4088 - accuracy: 0.8021 - val_loss: 0.4159 - val_accuracy: 0.7970
Epoch 20/20
40/40 - 0s - loss: 0.4118 - accuracy: 0.8002 - val_loss: 0.4155 - val_accuracy: 0.8025
plot1(history3)
model3.evaluate(X_test, y_test, batch_size=BATCH_SIZE, verbose=2)
13/13 - 0s - loss: 0.4104 - accuracy: 0.7999
[0.4104180335998535, 0.7998741269111633]
Model 4: Improve the Models¶
In addition to regularization and dropouts, we can further improve the model by increasing the model complexity.
In particular, we can increase the depths and widths of the network layers.
Let’s try stacking two RNN layers.
Tip
When we stack two sequence layers (e.g., RNN), we need to make sure that the hidden states (outputs) of the first sequence layer at all timesteps are properly passed onto the next sequence layer, not just the hidden state (output) of the last timestep.
In keras, this usually means that we need to set the argument return_sequences=True in a sequence layer (e.g., SimpleRNN, LSTM, GRU etc).
## Define embedding dimension
MBEDDING_DIM = 128
## Define model
model4 = Sequential()
model4.add(
layers.Embedding(input_dim=vocab_size,
output_dim=EMBEDDING_DIM,
input_length=max_len,
mask_zero=True))
model4.add(
layers.SimpleRNN(16,
activation="relu",
name="RNN_layer_1",
dropout=0.2,
recurrent_dropout=0.2,
return_sequences=True)
) ## To ensure the hidden states of all timesteps are pased down to next layer
model4.add(
layers.SimpleRNN(16,
activation="relu",
name="RNN_layer_2",
dropout=0.2,
recurrent_dropout=0.2))
model4.add(layers.Dense(1, activation="sigmoid", name="output"))
## Compile model
model4.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=["accuracy"])
plot_model(model4, show_shapes=True)
history4 = model4.fit(X_train,
y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
verbose=2,
validation_split=VALIDATION_SPLIT)
Epoch 1/20
40/40 - 2s - loss: 0.6455 - accuracy: 0.6282 - val_loss: 0.5971 - val_accuracy: 0.6318
Epoch 2/20
40/40 - 0s - loss: 0.5759 - accuracy: 0.6611 - val_loss: 0.5218 - val_accuracy: 0.7286
Epoch 3/20
40/40 - 0s - loss: 0.5156 - accuracy: 0.7384 - val_loss: 0.4750 - val_accuracy: 0.7758
Epoch 4/20
40/40 - 0s - loss: 0.4875 - accuracy: 0.7537 - val_loss: 0.4614 - val_accuracy: 0.7789
Epoch 5/20
40/40 - 0s - loss: 0.4731 - accuracy: 0.7589 - val_loss: 0.4487 - val_accuracy: 0.7828
Epoch 6/20
40/40 - 0s - loss: 0.4581 - accuracy: 0.7773 - val_loss: 0.4461 - val_accuracy: 0.7844
Epoch 7/20
40/40 - 0s - loss: 0.4504 - accuracy: 0.7785 - val_loss: 0.4396 - val_accuracy: 0.7884
Epoch 8/20
40/40 - 0s - loss: 0.4466 - accuracy: 0.7785 - val_loss: 0.4367 - val_accuracy: 0.7891
Epoch 9/20
40/40 - 0s - loss: 0.4496 - accuracy: 0.7821 - val_loss: 0.4360 - val_accuracy: 0.7876
Epoch 10/20
40/40 - 0s - loss: 0.4424 - accuracy: 0.7813 - val_loss: 0.4318 - val_accuracy: 0.7954
Epoch 11/20
40/40 - 0s - loss: 0.4393 - accuracy: 0.7838 - val_loss: 0.4286 - val_accuracy: 0.7939
Epoch 12/20
40/40 - 0s - loss: 0.4384 - accuracy: 0.7887 - val_loss: 0.4282 - val_accuracy: 0.7899
Epoch 13/20
40/40 - 0s - loss: 0.4359 - accuracy: 0.7813 - val_loss: 0.4283 - val_accuracy: 0.7946
Epoch 14/20
40/40 - 0s - loss: 0.4316 - accuracy: 0.7899 - val_loss: 0.4204 - val_accuracy: 0.7994
Epoch 15/20
40/40 - 0s - loss: 0.4321 - accuracy: 0.7933 - val_loss: 0.4222 - val_accuracy: 0.7946
Epoch 16/20
40/40 - 0s - loss: 0.4277 - accuracy: 0.7895 - val_loss: 0.4216 - val_accuracy: 0.7954
Epoch 17/20
40/40 - 0s - loss: 0.4310 - accuracy: 0.7887 - val_loss: 0.4206 - val_accuracy: 0.7899
Epoch 18/20
40/40 - 0s - loss: 0.4265 - accuracy: 0.7909 - val_loss: 0.4227 - val_accuracy: 0.7923
Epoch 19/20
40/40 - 0s - loss: 0.4291 - accuracy: 0.7925 - val_loss: 0.4223 - val_accuracy: 0.7978
Epoch 20/20
40/40 - 0s - loss: 0.4206 - accuracy: 0.7972 - val_loss: 0.4190 - val_accuracy: 0.7954
plot1(history4)
model4.evaluate(X_test, y_test, batch_size=BATCH_SIZE, verbose=2)
13/13 - 0s - loss: 0.4167 - accuracy: 0.7961
[0.41671815514564514, 0.7960981726646423]
Model 5: Bidirectional¶
We can also increase the model complexity in at least two possible ways:
Use more advanced RNNs, such as LSTM or GRU
Process the sequence in two directions
Increase the hidden nodes of the RNN/LSTM
Now let’s try the more sophisticated RNN, LSTM, and with bidirectional sequence processing and add more nodes to the LSTM layer.
## Define embedding dimension
EMBEDDING_DIM = 128
## Define model
model5 = Sequential()
model5.add(
layers.Embedding(input_dim=vocab_size,
output_dim=EMBEDDING_DIM,
input_length=max_len,
mask_zero=True))
model5.add(
layers.Bidirectional( ## Bidirectional sequence processing
layers.LSTM(32,
activation="relu",
name="lstm_layer_1",
dropout=0.2,
recurrent_dropout=0.5,
return_sequences=True)))
model5.add(
layers.Bidirectional( ## Bidirectional sequence processing
layers.LSTM(32,
activation="relu",
name="lstm_layer_2",
dropout=0.2,
recurrent_dropout=0.5)))
model5.add(layers.Dense(1, activation="sigmoid", name="output"))
model5.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=["accuracy"])
plot_model(model5, show_shapes=True)
history5 = model5.fit(X_train,
y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
verbose=2,
validation_split=VALIDATION_SPLIT)
Epoch 1/20
40/40 - 9s - loss: 0.6573 - accuracy: 0.6249 - val_loss: 0.6254 - val_accuracy: 0.6310
Epoch 2/20
40/40 - 2s - loss: 0.5830 - accuracy: 0.6491 - val_loss: 0.5668 - val_accuracy: 0.7286
Epoch 3/20
40/40 - 1s - loss: 0.5255 - accuracy: 0.7429 - val_loss: 0.5030 - val_accuracy: 0.7600
Epoch 4/20
40/40 - 1s - loss: 0.4853 - accuracy: 0.7685 - val_loss: 0.4772 - val_accuracy: 0.7789
Epoch 5/20
40/40 - 1s - loss: 0.4718 - accuracy: 0.7712 - val_loss: 0.4619 - val_accuracy: 0.7828
Epoch 6/20
40/40 - 1s - loss: 0.4602 - accuracy: 0.7712 - val_loss: 0.4555 - val_accuracy: 0.7821
Epoch 7/20
40/40 - 1s - loss: 0.4521 - accuracy: 0.7779 - val_loss: 0.4480 - val_accuracy: 0.7931
Epoch 8/20
40/40 - 1s - loss: 0.4404 - accuracy: 0.7836 - val_loss: 0.4402 - val_accuracy: 0.7946
Epoch 9/20
40/40 - 1s - loss: 0.4379 - accuracy: 0.7913 - val_loss: 0.4401 - val_accuracy: 0.7939
Epoch 10/20
40/40 - 1s - loss: 0.4293 - accuracy: 0.7897 - val_loss: 0.4465 - val_accuracy: 0.7891
Epoch 11/20
40/40 - 1s - loss: 0.4214 - accuracy: 0.7984 - val_loss: 0.4369 - val_accuracy: 0.7962
Epoch 12/20
40/40 - 1s - loss: 0.4137 - accuracy: 0.7994 - val_loss: 0.4355 - val_accuracy: 0.8017
Epoch 13/20
40/40 - 1s - loss: 0.4088 - accuracy: 0.8013 - val_loss: 0.4334 - val_accuracy: 0.8025
Epoch 14/20
40/40 - 1s - loss: 0.4064 - accuracy: 0.8039 - val_loss: 0.4281 - val_accuracy: 0.8017
Epoch 15/20
40/40 - 1s - loss: 0.4009 - accuracy: 0.8070 - val_loss: 0.4328 - val_accuracy: 0.7946
Epoch 16/20
40/40 - 1s - loss: 0.3996 - accuracy: 0.8049 - val_loss: 0.4281 - val_accuracy: 0.7962
Epoch 17/20
40/40 - 1s - loss: 0.3979 - accuracy: 0.8055 - val_loss: 0.4435 - val_accuracy: 0.7978
Epoch 18/20
40/40 - 2s - loss: 0.3924 - accuracy: 0.8098 - val_loss: 0.4314 - val_accuracy: 0.8025
Epoch 19/20
40/40 - 2s - loss: 0.3916 - accuracy: 0.8131 - val_loss: 0.4220 - val_accuracy: 0.8017
Epoch 20/20
40/40 - 2s - loss: 0.3882 - accuracy: 0.8129 - val_loss: 0.4297 - val_accuracy: 0.7931
plot1(history5)
model5.evaluate(X_test, y_test, batch_size=BATCH_SIZE, verbose=2)
13/13 - 0s - loss: 0.4262 - accuracy: 0.8093
[0.4262401759624481, 0.8093140125274658]
2.8. Check Embeddings¶
Compared to one-hot encodings of characters, embeddings may include more information relating to the characteristics (semantics?) of the characters.
We can extract the embedding layer and apply dimensional reduction techniques (i.e., TSNE) to see how embeddings capture the relationships in-between characters.
## A name in sequence from test set
print(X_test_texts[10])
print(X_test[10])
Kimberlyn
[ 0 0 0 0 0 0 18 3 12 15 2 5 6 11 4]
## Extract Corpus Dictionary (mapping of chars and integer indices)
ind2char = tokenizer.index_word
[ind2char.get(i) for i in X_test[10] if ind2char.get(i) != None]
['k', 'i', 'm', 'b', 'e', 'r', 'l', 'y', 'n']
## Extract the embedding layer (its weights matrix)
char_vectors = model5.layers[0].get_weights()[0]
print(char_vectors.shape) ## embedding shape (vocab_size, embed_dim)
print(char_vectors[1,:]) ## first char embeddings
(29, 128)
[-0.12168911 -0.09770504 0.13036579 0.05517732 0.05122091 -0.02791139
0.09014089 0.07347665 0.11493888 0.08239079 0.09154149 -0.10337761
-0.05760954 -0.12624586 0.1947672 -0.06125323 -0.02121914 -0.09557756
0.11781327 0.11854131 -0.02826954 -0.08324181 0.06485433 -0.09577868
0.16240902 -0.07652633 -0.08850154 0.01714855 -0.03669919 -0.08458259
-0.06329387 -0.1134198 -0.10314479 -0.0983581 -0.14569582 0.03433445
0.2084191 0.17178224 0.13684429 -0.09997117 0.14710589 -0.05349435
-0.01036222 -0.14729305 -0.10574742 -0.07146644 -0.11271249 -0.10739706
-0.10569047 0.21600746 -0.11666907 -0.00893974 0.11803301 0.11491597
0.15829618 0.13300136 -0.06793297 0.09997653 -0.13660857 0.08470872
-0.09365635 0.06656562 -0.14993365 0.0723782 -0.12493811 -0.05701834
-0.10275101 0.08835832 0.10170632 -0.11736683 0.13231203 0.1426191
0.12963526 -0.10411806 -0.04174949 -0.07908826 0.14218315 0.12732531
0.11016922 -0.10773734 0.05658606 -0.0642297 -0.07545524 0.12026434
0.13509122 0.10849994 0.16050701 -0.14851795 0.00041629 0.0175813
0.09823687 0.01593449 0.10756197 -0.10396273 -0.14702412 0.06906382
0.03229571 -0.02547304 -0.09972943 0.11553532 0.04354261 0.14496653
0.00341315 0.13248928 -0.13421129 0.11232341 0.10659309 0.11777832
0.04990724 0.00435498 -0.19152316 -0.11743353 0.05700824 0.06376923
0.09228779 0.13512447 -0.12372506 0.10561202 -0.16579406 0.01316056
0.0456382 0.08121356 0.12451012 -0.07125925 -0.01008594 0.09884214
0.08438003 0.10801204]
labels = [char for (ind, char) in tokenizer.index_word.items()]
labels.insert(0, None)
labels
[None,
'a',
'e',
'i',
'n',
'r',
'l',
'o',
't',
's',
'd',
'y',
'm',
'h',
'c',
'b',
'u',
'g',
'k',
'j',
'v',
'f',
'p',
'w',
'z',
'x',
'q',
'-',
' ']
## Visulizing char embeddings via dimensional reduction techniques
tsne = TSNE(n_components=2, random_state=0, n_iter=5000, perplexity=3)
np.set_printoptions(suppress=True)
T = tsne.fit_transform(char_vectors)
labels = labels
plt.figure(figsize=(10, 7), dpi=150)
plt.scatter(T[:, 0], T[:, 1], c='orange', edgecolors='r')
for label, x, y in zip(labels, T[:, 0], T[:, 1]):
plt.annotate(label,
xy=(x + 1, y + 1),
xytext=(0, 0),
textcoords='offset points')
2.9. Issues of Word/Character Representations¶
One-hot encoding does not indicate semantic relationships between characters.
For deep learning NLP, it is preferred to convert one-hot encodings of words/characters into embeddings, which are argued to include more semantic information of the tokens.
Now the question is how to train and create better word embeddings.
There are at least two alternatives:
We can train the embeddings along with our current NLP task.
We can use pre-trained embeddings from other unsupervised learning (transfer learning).
We will come back to this issue later.
2.10. Hyperparameter Tuning¶
Note
Please install keras tuner module in your current conda:
pip install -U keras-tuner
or
conda install -c conda-forge keras-tuner
Like feature-based ML methods, neural networks also come with many hyperparameters, which require default values.
Typical hyperparameters include:
Number of nodes for the layer
Learning Rates
We can utilize the module,
keras-tuner, to fine-tune these hyperparameters (i.e., to find the values that optimize the model performance).
Steps for Keras Tuner
First, wrap the model definition in a function, which takes a single
hpargument.Inside this function, replace any value we want to tune with a call to hyperparameter sampling methods, e.g.
hp.Int()orhp.Choice(). The function should return a compiled model.Next, instantiate a
tunerobject specifying our optimization objective and other search parameters.Finally, start the search with the
search()method, which takes the same arguments asModel.fit()in keras.When the search is over, we can retrieve the best model and a summary of the results from the
tunner.
## confirm if the right kernel is being used
# import sys
# sys.executable
## Wrap model definition in a function
## and specify the parameters needed for tuning
# def build_model(hp):
# model1 = keras.Sequential()
# model1.add(keras.Input(shape=(max_len,)))
# model1.add(layers.Dense(hp.Int('units', min_value=32, max_value=128, step=32), activation="relu", name="dense_layer_1"))
# model1.add(layers.Dense(hp.Int('units', min_value=32, max_value=128, step=32), activation="relu", name="dense_layer_2"))
# model1.add(layers.Dense(2, activation="softmax", name="output"))
# model1.compile(
# optimizer=keras.optimizers.Adam(
# hp.Choice('learning_rate',
# values=[1e-2, 1e-3, 1e-4])),
# loss='sparse_categorical_crossentropy',
# metrics=['accuracy'])
# return model1
## wrap model definition and compiling
def build_model(hp):
m = Sequential()
m.add(
layers.Embedding(
input_dim=vocab_size,
output_dim=hp.Int(
'output_dim', ## tuning 2
min_value=32,
max_value=128,
step=32),
input_length=max_len,
mask_zero=True))
m.add(
layers.Bidirectional(
layers.LSTM(
hp.Int('units', min_value=16, max_value=64,
step=16), ## tuning 1
activation="relu",
dropout=0.2,
recurrent_dropout=0.2)))
m.add(layers.Dense(1, activation="sigmoid", name="output"))
m.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=["accuracy"])
return m
## This is to clean up the temp dir from the tuner
## Every time we re-start the tunner, it's better to keep the temp dir clean
if os.path.isdir('my_dir'):
shutil.rmtree('my_dir')
The
max_trialsvariable represents the maximum number of the hyperparameter combinations that will be tested by the tuner (because sometimes the combinations are too many and the max number can limit the time in fine-tuning).The
execution_per_trialvariable is the number of models that should be built and fit for each trial for robustness purposes (i.e., consistent results).
## Instantiate the tunner
tuner = kerastuner.tuners.RandomSearch(build_model,
objective='val_accuracy',
max_trials=10,
executions_per_trial=2,
directory='my_dir')
## Check the tuner's search space
tuner.search_space_summary()
Search space summary
Default search space size: 2
output_dim (Int)
{'default': None, 'conditions': [], 'min_value': 32, 'max_value': 128, 'step': 32, 'sampling': None}
units (Int)
{'default': None, 'conditions': [], 'min_value': 16, 'max_value': 64, 'step': 16, 'sampling': None}
%%time
## Start tuning with the tuner
tuner.search(X_train, y_train, validation_split=VALIDATION_SPLIT, batch_size=BATCH_SIZE)
Trial 10 Complete [00h 00m 10s]
val_accuracy: 0.6309992074966431
Best val_accuracy So Far: 0.6353265047073364
Total elapsed time: 00h 01m 45s
INFO:tensorflow:Oracle triggered exit
CPU times: user 2min 55s, sys: 50.7 s, total: 3min 46s
Wall time: 1min 45s
## Retrieve the best models from the tuner
models = tuner.get_best_models(num_models=2)
plot_model(models[0], show_shapes=True)
## Retrieve the summary of results from the tuner
tuner.results_summary()
Results summary
Results in my_dir/untitled_project
Showing 10 best trials
Objective(name='val_accuracy', direction='max')
Trial summary
Hyperparameters:
output_dim: 128
units: 32
Score: 0.6353265047073364
Trial summary
Hyperparameters:
output_dim: 96
units: 48
Score: 0.6341463327407837
Trial summary
Hyperparameters:
output_dim: 64
units: 48
Score: 0.6321793794631958
Trial summary
Hyperparameters:
output_dim: 128
units: 16
Score: 0.6317859888076782
Trial summary
Hyperparameters:
output_dim: 64
units: 32
Score: 0.6309992074966431
Trial summary
Hyperparameters:
output_dim: 32
units: 48
Score: 0.6309992074966431
Trial summary
Hyperparameters:
output_dim: 32
units: 16
Score: 0.6309992074966431
Trial summary
Hyperparameters:
output_dim: 96
units: 16
Score: 0.6309992074966431
Trial summary
Hyperparameters:
output_dim: 32
units: 64
Score: 0.6309992074966431
Trial summary
Hyperparameters:
output_dim: 64
units: 64
Score: 0.6309992074966431
2.11. Explanation¶
Train Model with the Tuned Hyperparameters¶
EMBEDDING_DIM = 128
HIDDEN_STATE=32
model6 = Sequential()
model6.add(
layers.Embedding(input_dim=vocab_size,
output_dim=EMBEDDING_DIM,
input_length=max_len,
mask_zero=True))
model6.add(
layers.Bidirectional(
layers.LSTM(HIDDEN_STATE,
activation="relu",
name="lstm_layer",
dropout=0.2,
recurrent_dropout=0.5)))
model6.add(layers.Dense(1, activation="sigmoid", name="output"))
model6.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=["accuracy"])
plot_model(model6)
history6 = model6.fit(X_train,
y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
verbose=2,
validation_split=VALIDATION_SPLIT)
Epoch 1/20
40/40 - 6s - loss: 0.6629 - accuracy: 0.6178 - val_loss: 0.6276 - val_accuracy: 0.6310
Epoch 2/20
40/40 - 1s - loss: 0.5867 - accuracy: 0.6617 - val_loss: 0.5415 - val_accuracy: 0.7411
Epoch 3/20
40/40 - 1s - loss: 0.4926 - accuracy: 0.7581 - val_loss: 0.4786 - val_accuracy: 0.7773
Epoch 4/20
40/40 - 1s - loss: 0.4570 - accuracy: 0.7803 - val_loss: 0.4535 - val_accuracy: 0.7821
Epoch 5/20
40/40 - 1s - loss: 0.4369 - accuracy: 0.7860 - val_loss: 0.4413 - val_accuracy: 0.7868
Epoch 6/20
40/40 - 1s - loss: 0.4289 - accuracy: 0.7889 - val_loss: 0.4336 - val_accuracy: 0.7884
Epoch 7/20
40/40 - 1s - loss: 0.4248 - accuracy: 0.7952 - val_loss: 0.4278 - val_accuracy: 0.8017
Epoch 8/20
40/40 - 1s - loss: 0.4162 - accuracy: 0.8025 - val_loss: 0.4299 - val_accuracy: 0.8025
Epoch 9/20
40/40 - 1s - loss: 0.4110 - accuracy: 0.8006 - val_loss: 0.4241 - val_accuracy: 0.8088
Epoch 10/20
40/40 - 1s - loss: 0.4045 - accuracy: 0.8045 - val_loss: 0.4276 - val_accuracy: 0.8033
Epoch 11/20
40/40 - 1s - loss: 0.4005 - accuracy: 0.8047 - val_loss: 0.4231 - val_accuracy: 0.8041
Epoch 12/20
40/40 - 1s - loss: 0.3999 - accuracy: 0.8023 - val_loss: 0.4189 - val_accuracy: 0.8072
Epoch 13/20
40/40 - 1s - loss: 0.3978 - accuracy: 0.8061 - val_loss: 0.4191 - val_accuracy: 0.8041
Epoch 14/20
40/40 - 1s - loss: 0.3974 - accuracy: 0.8063 - val_loss: 0.4165 - val_accuracy: 0.8096
Epoch 15/20
40/40 - 1s - loss: 0.3939 - accuracy: 0.8061 - val_loss: 0.4158 - val_accuracy: 0.8041
Epoch 16/20
40/40 - 1s - loss: 0.3951 - accuracy: 0.8051 - val_loss: 0.4178 - val_accuracy: 0.8143
Epoch 17/20
40/40 - 1s - loss: 0.3897 - accuracy: 0.8129 - val_loss: 0.4134 - val_accuracy: 0.8057
Epoch 18/20
40/40 - 1s - loss: 0.3901 - accuracy: 0.8102 - val_loss: 0.4158 - val_accuracy: 0.8017
Epoch 19/20
40/40 - 1s - loss: 0.3879 - accuracy: 0.8096 - val_loss: 0.4110 - val_accuracy: 0.8088
Epoch 20/20
40/40 - 1s - loss: 0.3863 - accuracy: 0.8141 - val_loss: 0.4101 - val_accuracy: 0.8065
plot2(history6)
explainer = LimeTextExplainer(class_names=['female','male'], char_level=True)
def model_predict_pipeline(text):
_seq = tokenizer.texts_to_sequences(text)
_seq_pad = keras.preprocessing.sequence.pad_sequences(_seq, maxlen=max_len)
return np.array([[float(1-x), float(x)] for x in model6.predict(np.array(_seq_pad))])
#return model6.predict(np.array(_seq_pad))
text_id = 12
print(X_test_texts[text_id])
model_predict_pipeline([X_test_texts[text_id]])
Star
array([[0.19570321, 0.80429679]])
exp = explainer.explain_instance(X_test_texts[text_id],
model_predict_pipeline,
num_features=10,
top_labels=1)
exp.show_in_notebook(text=True)
y_test[text_id]
0
exp = explainer.explain_instance('Tim',
model_predict_pipeline,
num_features=10,
top_labels=1)
exp.show_in_notebook(text=True)
exp = explainer.explain_instance('Michaelis',
model_predict_pipeline,
num_features=10,
top_labels=1)
exp.show_in_notebook(text=True)
exp = explainer.explain_instance('Sidney',
model_predict_pipeline,
num_features=10,
top_labels=1)
exp.show_in_notebook(text=True)
exp = explainer.explain_instance('Timber',
model_predict_pipeline,
num_features=10,
top_labels=1)
exp.show_in_notebook(text=True)
exp = explainer.explain_instance('Alvin',
model_predict_pipeline,
num_features=10,
top_labels=1)
exp.show_in_notebook(text=True)
2.12. References¶
Chollet (2017), Ch 3 and Ch 4